package com.cloudweb.oa.aop;

import cn.js.fan.db.ResultIterator;
import cn.js.fan.db.ResultRecord;
import cn.js.fan.db.SQLFilter;
import cn.js.fan.util.DateUtil;
import cn.js.fan.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudwebsoft.framework.db.JdbcTemplate;
import com.cloudwebsoft.framework.util.LogUtil;
import com.redmoon.oa.person.PlanDb;
import org.aspectj.lang.JoinPoint;
import com.cloudweb.oa.vo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.TextStyle;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
     * Title:     SpringBoot拦截器
     * Description:罗列日期、删除数据库残留
     * Date：     2024-06-18
     */
@Component
@Aspect
public class UserPlanAspect {
    @Pointcut("execution(  * com.cloudweb.oa.controller.UserPlanController.create(..))")
    private void create(){
    }
    @Pointcut("execution(  * com.cloudweb.oa.controller.UserPlanController.del(..))")
    private void delete(){
    }
    // doAround：用于方法调用后
    @Around("create()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 取出拼接后的字符串id
        Object res = null;
        String ids = "";
        res = joinPoint.proceed();
        if (res instanceof Result) {
            Result<?> result = (Result<?>) res;
            if (result.getData() instanceof JSONObject) {
                JSONObject json = (JSONObject) result.getData();
                ids = json.getString("ids");
            }
        }
        LogUtil.getLog(getClass()).info("res=" + res.toString());
        String sqlInsert = "insert into ft_ldrcrq (pId, idate, flowTypeCode, date_week, is_am, is_pm) " +
                "values(?,?,?,?,?,?)";
        JdbcTemplate jt = new JdbcTemplate();
        try {
            Date middleDate, beginDate, endDate;
            int pID;
            jt.setAutoClose(false);
            PlanDb pd = new PlanDb();
            String[] ary = ids.split(",");
            for (String strId : ary) {
                int id = StrUtil.toInt(strId, -1);
                pd = pd.getPlanDb(id);

                pID = id;
                beginDate = pd.getMyDate();
                endDate = pd.getEndDate();
                middleDate = beginDate;
                // 使用calendar来增加天数
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(middleDate);

//                DayOfWeek weekday = middleDate.getDayOfWeek();
//                SimpleDateFormat sdf = new SimpleDateFormat("EEEE", Locale.CHINA); // EEEE代表星期几的全称，Locale.CHINA为星期
//                String weekday = sdf.format(middleDate);
                // 判断日期小于等于结束日期
                int i=1;
                while (!calendar.getTime().after(endDate)) {
                    // 转换日期类型
                    Instant instant = middleDate.toInstant();
                    ZoneId zone = ZoneId.of("Asia/Shanghai"); // 特定时区
                    ZonedDateTime zdt = instant.atZone(zone);
                    LocalDate localDate = zdt.toLocalDate();
                    // 使用 java.time 包获取中文星期几
                    DayOfWeek dayOfWeek = localDate.getDayOfWeek();
                    String chineseWeekday = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.SIMPLIFIED_CHINESE);
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
                    // 使用SimpleDateFormat对象的format方法将Date转换为字符串
                    String dateString = sdf.format(middleDate);
                    // 拼接（-月-日（星期））格式
                    String dateWeek = dateString + "(" + chineseWeekday +")";

                    int isAm = 0;
                    int isPm = 0;
                    int amHour = beginDate.getHours();
                    int pmHour = endDate.getHours();
                    // 若相等判断上下午时间
                    if (DateUtil.isSameDay(middleDate, endDate)) {
                        if (amHour >= 0 && amHour < 12 && pmHour >=0 && pmHour< 12) {
                            isAm = 1;
                            isPm = 0;
                        } else if (amHour >= 12 && amHour < 24 && pmHour >= 12 && pmHour< 24){
                            isAm = 0;
                            isPm = 1;
                        } else if (amHour >= 0 && amHour < 12 && pmHour >= 12 && pmHour< 24) {
                            isAm = 1;
                            isPm = 1;
                        }
                    } else {
                        isAm = 1;
                        isPm = 1;
                    }
//                    if (DateUtil.compare(middleDate, endDate) == 2) {
//
//                    }
//                    if (endDate.after(beginDate)) {
//                        pmHour = 23;
//                    }
//                       if (amHour >= 0 && amHour < 12 && pmHour >=0 && pmHour< 12) {
//                            isAm = 1;
//                            isPm = 0;
//                        } else if (amHour >= 12 && amHour < 24 && pmHour >= 12 && pmHour< 24){
//                            isAm = 0;
//                            isPm = 1;
//                        } else {
//                           isAm = 1;
//                           isPm = 1;
//                       }

                    jt.executeUpdate(sqlInsert, new Object[]{pID, middleDate, i, dateWeek, isAm, isPm});
                    i++;
                    // 每次循环增加天数一天
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    middleDate = calendar.getTime();
                }
            }
        }catch (SQLException e){
            LogUtil.getLog(getClass()).error(e);
        } finally {
            jt.close();
        }
        return res;
    }

//     删除数据库记录
    @Around("delete()")
    public Object doAroundDel(ProceedingJoinPoint joinPoint) throws Throwable {
        Object res = null;
        String ids = "";
        int id = 0;
        res = joinPoint.proceed();

        if (res instanceof Result) {
            Result<?> result = (Result<?>) res;
            // 检查data是否是JSONObject，并尝试获取id
            if (result.getData() instanceof JSONObject) {
                JSONObject json = (JSONObject) result.getData();
                id = (int) json.get("id");
            }
        }
        LogUtil.getLog(getClass()).info("res=" + res.toString());

        String sqlDel = "delete from ft_ldrcrq where pId=?";
        JdbcTemplate jt = new JdbcTemplate();
        try {
            int pID;
            pID = id;
            jt.executeUpdate(sqlDel, new Object[]{pID});
        } catch (SQLException e) {
            LogUtil.getLog(getClass()).error(e);
        }
        return res;
    }


    @After("create()")
    public void afterCreate(JoinPoint joinPoint) throws SQLException{
        Object[] args = joinPoint.getArgs();
        String name = joinPoint.getSignature().getName();
        System.out.println(Arrays.asList(args).toString() +"  "+ name);
        //从日程安排数据库中获取mydate和enddate向新表单中写入间隔日期
//        JSONArray jsonArray = new JSONArray();
//        JdbcTemplate jt = new JdbcTemplate();
//        String sql = "select p.id, DATE_FORMAT(myDate, '%Y-%m-%d') as myDate1, DATE_FORMAT(endDate, '%Y-%m-%d') as endDate1 from user_plan p,users u,dept_user d" +
//                     " where p.userName=u.name and u.name=d.USER_NAME and p.action_type=0 and d.DEPT_CODE NOT IN(00090001, 00090002, 00090003, 00090004, 00090005, 00090006, 00090007, 00090008, 00090009, 0005)";
//        String sqlInsert = "insert into ft_ldrcrq (pId, date, flowTypeCode) values(?,?,?)";
//        String myDate, myDate1;
//        Date middleDate,  beginDate, endDate;
//        int pID;
//        ResultIterator ri1 = jt.executeQuery(sql);
//        while(ri1.hasNext()) {
//            JSONObject jsonActivity = new JSONObject();
//            ResultRecord rr1 = ri1.next();
//            // 取出对应的开始和结束时间string
//            pID = rr1.getInt(1);
//            myDate = rr1.getString(2);
//            myDate1 = rr1.getString(3);
//            beginDate = DateUtil.parse(myDate, "yyyy-MM-dd");
//            endDate = DateUtil.parse(myDate1, "yyyy-MM-dd");
//            middleDate = beginDate;
//            // 使用calendar来增加天数
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(middleDate);
//            // 判断日期小于等于结束日期
//            boolean re = true;
//            int i=1;
//            while (!calendar.getTime().after(endDate)) {
//                try {
//                    re = jt.executeUpdate(sqlInsert, new Object[]{pID, middleDate, i}) == 1;
//                    i++;
//                } catch (SQLException e) {
//                    LogUtil.getLog(getClass()).error(e);
//                }
//                // 每次循环增加天数一天
//                calendar.add(Calendar.DAY_OF_MONTH, 1);
//                middleDate = calendar.getTime();
//            }
//        }
    }
}

